package com.zhu.wechat.service;

import com.zhu.wechat.Dao.RoomRepository;
import com.zhu.wechat.entity.Room;

import com.zhu.wechat.util.WechatConfigUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpMessageServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class SendWxCpMsgService {
    private static final String USER_INFO = "https://open.weixin.qq.com/connect/oauth2/authorize?";
    private static final Logger logger = LoggerFactory.getLogger(SendWxCpMsgService.class);
    @Value("${wx-cp-config.corpid}")
    private String appid;
    @Value("${wx-cp-config.redirectUrl}")
    private String redirectUrl;
    @Value("${wx-cp-config.agentid}")
    private String agentid;
    @Autowired
    private RoomRepository roomRepository;

    public void sendToWxCp(String username) {
        WxCpMessageServiceImpl wxCpMessageService = new WxCpMessageServiceImpl(WechatConfigUtil.getWxCpService());
        WxCpMessage wxCpMessage = new WxCpMessage();
        wxCpMessage.setSafe("0");
        wxCpMessage.setMsgType("textcard");  // 设置消息形式，这里设置为卡片消息
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        wxCpMessage.setToUser(username);

        List<Room> rooms = roomRepository.findAll();  //

        for (Room room : rooms) {
            if (room.getRoomStatus() == 1 && room.getUsername().equals(username)) {  //
                wxCpMessage.setTitle("房间打扫" + room.getRoomNumber());
                wxCpMessage.setDescription("您要打扫的房间为" + room.getRoomNumber() +
                        "请尽快前往！"
                        + "\n" + "当前时间为："
                        + time + "\n"
                        + "点击下方登录查看");

                String authUrl = USER_INFO
                        + "appid=" + appid
                        + "&redirect_uri=" + URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8)
                        + "&response_type=code"
                        + "&scope=snsapi_base"
                        + "&state=111"
                        + "&agentid=" + agentid
                        + "#wechat_redirect";

                wxCpMessage.setUrl(authUrl);
                wxCpMessage.setBtnTxt("前往查看");

                try {
                    wxCpMessageService.send(wxCpMessage);  // 发送消息
                } catch (WxErrorException e) {
                    logger.error("发送信息接口调用出错", e);
                }
            }
        }
    }

    public List<Room> getAllRooms() {
       return roomRepository.findAll();
    }
}
